package com.huatai.exchange.load;

import com.faneui.common.bean.AbstractLogger;
import com.faneui.common.exception.BusinessException;
import com.faneui.common.utils.Constants;
import com.faneui.common.utils.ListUtils;
import com.faneui.common.utils.ZipUtils;
import com.huatai.exchange.conn.LocalConnection;
import com.huatai.exchange.dal.model.ExcFileLoadInfo;
import com.huatai.exchange.integration.base.service.FileOperateService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import java.io.File;
import java.util.List;
import java.util.Map;
import java.util.UUID;

public abstract class AbstractDataFileLoadService extends AbstractLogger implements DataFileLoadService {

    @Value("${tmp_file_path}")
    protected String tmpFilePath;

    @Autowired
    protected LocalConnection localConnection;

    @Autowired
    protected FileOperateService fileOperateService;

    @Override
    public String loadDataFile(ExcFileLoadInfo loadInfo, String tmpPath, List<String> fileNames, Map<String, Object> resvMap) throws BusinessException {
        // 先将文件存储
        // 如果是多个文件 则需要压缩
        String resultFileName = null;
        if (Constants.boolean_true.equals(loadInfo.getMoreFlag())) {
            String uploadFile = tmpFilePath + UUID.randomUUID().toString();
            if (fileNames.size() > 0) {
                ZipUtils.zip(uploadFile, tmpPath);
            } else {
                if (Constants.boolean_true.equals(loadInfo.getIsNullAble()))
                    throw new BusinessException("文件数为0，不处理");
            }
            resultFileName = uploadFile;
        } else {
            if (ListUtils.isEmpty(fileNames))
                throw new BusinessException("文件数为0，不处理");
            resultFileName = fileOperateService.uploadFile(new File(tmpPath + fileNames.get(0)));
        }
        // 数据 入库

        if (StringUtils.isNotBlank(loadInfo.getTableName()))
            loadDataInDataBase(loadInfo, fileNames, tmpPath, resvMap);
        return resultFileName;
    }

    abstract void loadDataInDataBase(ExcFileLoadInfo loadInfo, List<String> fileNames, String filePath, Map<String, Object> resvMap) throws BusinessException;


}
